/*
 * MIT License
 *
 * Copyright (c) 2024-2025 milkpotatoes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

export { };

const LocalUniversalKVStroe: typeof UniversalKVStroe = Reflect.get(globalThis, 'UniversalKVStroe');
const innerMap: WeakMap<URLSearchParams, UniversalKVStroe<string>> = new WeakMap();
const formatQueryValue = (val: string) => {
    return decodeURIComponent(val.replace(/\+/g, ' '));
}

const applySearchString = (that: URLSearchParams, search: string) => {
    const storage = innerMap.get(that)!;
    if (search === '') {
        storage.data = [];
        return;
    }
    if (search[0] === '?') {
        search = search.substring(1);
    }
    storage.data = search.split('&').map(e => {
        const pair = e.split('=');
        if (pair.length < 2) {
            pair.push('');
        }
        pair[1] = formatQueryValue(pair[1]);
        return pair;
    }) as [string, string][];
}
registerTempInnerMethod('applySearchString', applySearchString);

class URLSearchParams {
    constructor(options?: string | Object) {
        const storage = new LocalUniversalKVStroe<string>();
        innerMap.set(this, storage);
        if (options !== undefined && typeof options !== 'object' && typeof options !== 'string') options = String(options);
        if (typeof options === 'string') {
            applySearchString(this, options);
        } else if (typeof options === 'object' && options !== null) {
            if (Array.isArray(options)) {
                const data = options as Array<[string, string]>;
                for (let [k, v] of data) {
                    storage.data.push([k, formatQueryValue(v)]);
                }
                return;
            }
            const data = options as { [key: string]: any, entries?: () => Iterable<[string, string]> };
            for (let [k, v] of (data.entries ? data.entries() : Object.entries(options))) {
                storage.data.push([k, formatQueryValue(String(v))]);
            }
        };
    };

    get size(): number {
        return innerMap.get(this)!.size;
    };

    append(name: string, value: string): void {
        return innerMap.get(this)!.append(name, value);
    };
    delete(name: string, value?: string): void {
        return innerMap.get(this)!.delete(name, value);
    };
    entries(): Iterable<[string, string]> {
        return innerMap.get(this)!.entries();
    };
    forEach(callback: ForEachCallback<URLSearchParams, string>, thisArg?: Object): void {
        return innerMap.get(this)!.forEach(callback, this, thisArg);
    }
    get(name: string): string | null {
        return innerMap.get(this)!.get(name) ?? null;
    };
    getAll(name: string): string[] {
        return innerMap.get(this)!.getAll(name);
    };
    has(name: string): boolean {
        return innerMap.get(this)!.has(name);
    };
    keys(): Iterable<string> {
        return innerMap.get(this)!.keys();
    };
    set(name: string, value: string): void {
        return innerMap.get(this)!.set(name, value);
    };
    sort(): void {
        return innerMap.get(this)!.sort();
    }
    toString() {
        return innerMap.get(this)!.data.map(e => {
            return e[0] + '=' + encodeURI(e[1].replace(/ /g, '+')).replace(/#/g, '%23').replace(/,/g, '%2C');
        }).join('&');
    }
    values() {
        return innerMap.get(this)!.values();
    };
}

Object.defineProperty(globalThis, 'URLSearchParams', {
    value: URLSearchParams,
    enumerable: false,
    writable: true,
    configurable: true,
});
